/*
 * @Author: 刘慧东
 * @Date: 2024-08-01 13:40:31
 * @LastEditors: 刘慧东
 * @LastEditTime: 2024-08-01 13:48:14
 */
package gen

import (
	"os"
	"strings"

	"github.com/zeromicro/go-zero/tools/goctl/model/sql/parser"
	"github.com/zeromicro/go-zero/tools/goctl/model/sql/template"
	"github.com/zeromicro/go-zero/tools/goctl/util"
	"github.com/zeromicro/go-zero/tools/goctl/util/pathx"
)

func (g *defaultGenerator) genModelCmdMapperImpl(t parser.Table) (string, error) {

	text, err := pathx.LoadTemplate(category, findOneMethodTemplateFile, template.ClientMapperImpl)
	if err != nil {
		return "", err
	}

	tablename := t.Name.Source()
	camelTableName := t.Name.ToCamel()

	fields := []string{}

	for _, f := range t.Fields {
		fields = append(fields, "\""+f.Name.Source()+"\"")
	}

	mapper, err := util.With("mapperImpl").
		Parse(text).
		Execute(map[string]any{
			"table":                 tablename,
			"fields":                strings.Join(fields, ","),
			"upperStartCamelObject": camelTableName,
			"dataType":              t.PrimaryKey.DataType,
			"data":                  t,
		})
	if err != nil {
		return "", err
	}

	return mapper.String(), nil
}

func (g *defaultGenerator) genModelCmdMapper(t parser.Table) (string, error) {

	text, err := pathx.LoadTemplate(category, findOneMethodTemplateFile, template.ClientMapper)
	if err != nil {
		return "", err
	}

	tablename := t.Name.Source()
	camelTableName := t.Name.ToCamel()

	mapper, err := util.With("mapper").
		Parse(text).
		Execute(map[string]any{
			"table":                 tablename,
			"upperStartCamelObject": camelTableName,
			"data":                  t,
		})
	if err != nil {
		return "", err
	}

	return mapper.String(), nil
}

func (g *defaultGenerator) genModelCmdMain(mapperImpls string, mappers string) error {
	text, err := pathx.LoadTemplate(category, findOneMethodTemplateFile, template.ClientMapperImpls)
	if err != nil {
		return err
	}

	impls, err := util.With("mapperMapperImpls").
		Parse(text).
		GoFmt(true).
		Execute(map[string]any{
			"impls": mapperImpls,
		})
	if err != nil {
		return err
	}

	err = os.WriteFile("cmd/client/impls.go", impls.Bytes(), os.ModePerm)
	if err != nil {
		return err
	}

	text, err = pathx.LoadTemplate(category, findOneMethodTemplateFile, template.ClientMain)
	if err != nil {
		return err
	}
	main, err := util.With("mapperMain").
		Parse(text).
		Execute(map[string]any{
			"mappers": mappers,
		})
	if err != nil {
		return err
	}

	err = os.WriteFile("cmd/client/main.go", main.Bytes(), os.ModePerm)
	return err
}
